(function (w) {//
    // ——————————导航栏部分 开始——————————————

    // 切换专栏
    let artical_tab = document.querySelector('.artical');
    let classified_column_tab = document.querySelector('.classified_column');
    let artical_content = document.querySelector('.artical_content');
    let classified_column_content = document.querySelector('.classified_column_content');
    let artiInColumn = document.querySelector('.artiInColumn');
    let showArti = function () {
        classified_column_content.style.display = 'none';
        artiInColumn.style.display = 'none';
        artical_content.style.display = 'block';
    }
    let showCol = function () {
        artical_content.style.display = 'none';
        artiInColumn.style.display = 'none';
        column_list.style.display = 'block';
        classified_column_content.style.display = 'block';
        colH3.innerHTML = '分类专栏';
    }
    let showArtiInCol = function () {
        column_list.style.display = 'none';
        artical_content.style.display = 'none';
        classified_column_content.style.display = 'block';
        artiInColumn.style.display = 'block';
    }
    artical_tab.addEventListener('click', showArti);
    classified_column_tab.addEventListener('click', showCol);


    // 修改密码按钮
    let changePs_btn = document.querySelector('.changePs_btn');
    let changePs_bar = document.querySelector('.changePs_bar');
    let changePs_in = document.querySelector('.changePs_in');
    let oldPs_in = document.querySelector('.oldPs_in');
    changePs_btn.addEventListener('click', function () {
        showBar(changePs_bar);
        oldPs_in.focus();
    });
    // 修改密码框 (新密码)enter监听 
    changePs_in.addEventListener('keydown', function (e) {
        if (changePs_bar.style.display !== 'none') {
            if (e.key === 'Enter') {
                changePassword();
            }
        }
    });
    // 修改密码逻辑
    let changePs_comfirm_btn = document.querySelector('.changePs_comfirm_btn');
    let changePassword = function () {
        let oldPassword = oldPs_in.value;
        let newPassword = changePs_in.value;
        if (oldPassword === '' || newPassword === '') {
            console.log('输入不能为空');
            return;
        }
        // 发送添加分栏专栏请求
        ajax({
            method: 'PUT',
            url: urlRoot + 'login',
            data: {
                username: 'root',//默认修改root密码
                password: oldPassword,//旧密码
                newPassword,//新密码
            },
            header: {//post/put/delete 修改为 application/json
                'Content-type': 'application/json'
            },
        }).then((json) => {
            alert(json.meta.msg);
            closeBar(changePs_bar);
            oldPs_in.value = '';
            changePs_in.value = '';
        }, (error) => {
            alert(error);
            closeBar(changePs_bar);
        });
    }
    changePs_comfirm_btn.addEventListener('click', changePassword);

    // ———————————导航栏部分 结束——————————————





    //  ——————————文章专栏部分 开始————————————

    // 文章渲染
    let artical_list = document.querySelector('.artical_list');
    let artiTemplate = (dataId, artiTitle, createTime, artiClassName, artiClassId) => `
    <li data-id="${dataId}">
        <div class="arti_title">
            <span class="arti_title_span">${artiTitle}</span>
            <a href="javascript:;" class="arti_class_info" data-id="${artiClassId}">${artiClassName}</a>
        </div>
        <div class="arti_info">
            <span class="time">${util.formatDate(createTime)}</span>
            <div class="opt_box">
                <a href="javascript:;" class="edit_opt_box">编辑</a>
                <a href="javascript:;" class="check_opt_box">浏览</a>
                <a href="javascript:;" class="delete_opt_box">删除</a>
            </div>
        </div>
    </li>`
    let renderArticle = function () {
        ajax({
            method: 'GET',
            url: urlRoot + 'article/getArticle',
        }).then((json) => {
            artical_list.children[0].innerHTML = '';
            json.data.forEach(arti => {
                let li = util.str2Html(artiTemplate(arti.id, arti.title, arti.create_time, arti.class_name, arti.class_id));
                artical_list.querySelector('ul').appendChild(li);
            });
        }, (error) => {
            alert('渲染文章时发生错误：\n' + error);
        });
    }
    renderArticle();
    //手动渲染按钮
    let refreshArti_btn = document.querySelector('.refreshArti_btn');
    refreshArti_btn.addEventListener('click', renderArticle);

    // 添加文章
    let add_arti_btn = document.querySelector('.add_arti_btn');//Markdown编辑器
    add_arti_btn.addEventListener('click', function () {
        w.location.href = util.getCurrRootUrl() + 'editor.html';
    });
    // 文章管理 options （包含：编辑、浏览、删除）
    let delete_arti_bar = document.querySelector('.delete_arti_bar');//删除文章bar
    let arti_id;
    artical_list.addEventListener('click', async function (e) {
        let aname = e.target.className;
        let dataEle;
        if (aname === 'edit_opt_box' ||
            aname === 'check_opt_box' ||
            aname === 'delete_opt_box') {
            dataEle = e.target.parentNode.parentNode.parentNode;
            arti_id = dataEle.dataset.id;
        } else if (aname === 'arti_class_info') {
            col_id = e.target.dataset.id;
            col_title = e.target.textContent;
        } else {
            return;
        }
        if (aname === 'edit_opt_box') {
            w.location.href = `${util.getCurrRootUrl()}editor.html?id=${arti_id}`;
        } else if (aname === 'check_opt_box') {
            // 页面重定向到博客展示此文章页
            w.location.href = `${util.getCurrRootUrl()}showpage.html?id=${arti_id}`;
        } else if (aname === 'delete_opt_box') {
            // 删除文章
            showBar(delete_arti_bar);
        } else if (aname === 'arti_class_info') {
            renderArticleByClassId();
            showArtiInCol();
        }
    });

    // 删除文章 确认/取消按钮 及 事件绑定
    let artiDel_confrimBtn = document.querySelector('.artiDel_confrimBtn');
    let artiDel_cancelBtn = document.querySelector('.artiDel_cancelBtn');
    let deleteArticle = function () {
        ajax({
            method: 'DELETE',
            url: urlRoot + 'article/deleteArticle',
            data: { id: arti_id },
            header: {//post/put/delete 修改为 application/json
                'Content-type': 'application/json'
            },
        }).then((json) => {
            alert('删除文章id[' + json.data[0].id + ']成功!');
            renderArticle();
            closeBar(delete_arti_bar);
        }, (error) => {
            alert(error);
            closeBar(delete_arti_bar);
        });
    }
    artiDel_cancelBtn.addEventListener('click', function () {
        closeBar(delete_arti_bar);
    });
    artiDel_confrimBtn.addEventListener('click', deleteArticle);

    //  ——————————文章专栏部分 结束————————————





    //  ——————————分类专栏部分 开始————————————

    // 分类渲染
    let column_list = document.querySelector('.column_list');
    let colTemplate = (dataId, className, artiNum) => `
    <li data-id="${dataId}">
        <span class="col_name">${className}</span>
        <div class="opt_box">
            <a href="javascript:;" class="manage_opt_box">管理</a>
            <a href="javascript:;" class="edit_opt_box">编辑</a>
            <a href="javascript:;" class="delete_opt_box">删除</a>
        </div>
        <span class="artical_count">${artiNum} 篇文章</span>
    </li>`;
    let renderColumn = function () {
        column_list.children[0].innerHTML = '';//清空内容
        // 发送获取所有文章的请求
        ajax({
            method: 'GET',
            url: urlRoot + 'article/class',
        }).then((json) => {
            json.data.forEach(col => {
                if (col.article_total === undefined) {//没有文章
                    col.article_total = 0;
                }
                if (col.id === -1) {//未分类特殊处理
                    column_list.querySelector('ul').appendChild(util.str2Html(`
                    <li data-id="-1">
                        <span class="col_name">${col.class_name}</span>
                        <div class="opt_box">
                            <a href="javascript:;" class="manage_opt_box">管理</a>
                            <a href="javascript:;" class="edit_opt_box">编辑</a>
                        </div>
                        <span class="artical_count">${col.article_total} 篇文章</span>
                    </li>`));
                } else {
                    let html = util.str2Html(colTemplate(col.id, col.class_name, col.article_total));
                    column_list.querySelector('ul').appendChild(html);
                }
            });
        }, (error) => {
            alert('渲染页面时发生错误：\n' + error);
        });
    }
    renderColumn();
    //手动渲染按钮
    let refreshCol_btn = document.querySelector('.refreshCol_btn');
    refreshCol_btn.addEventListener('click', renderColumn);

    // 添加分类专栏
    let add_col_bar_btn = document.querySelector('.add_col_bar_btn');
    let add_col_bar_title = document.querySelector('.col_title_in');
    // 新建弹出模态框
    let add_column = document.querySelector('.add_column');
    let add_col_bar = document.querySelector('.add_col_bar');
    add_column.addEventListener('click', function () {
        showBar(add_col_bar);
        add_col_bar_title.focus();//获得输入框焦点
    });
    // 新建专栏框 enter 监听
    add_col_bar_title.addEventListener('keydown', function (e) {
        if (add_col_bar.style.display !== 'none') {
            if (e.key === 'Enter') {
                addColumn();
            }
        }
    })

    let addColumn = function () {
        let colTitle = add_col_bar_title.value;
        if (colTitle === '') {
            // 优化提示
            alert('输入不能为空');
            return;
        }
        // 发送添加分类专栏请求
        ajax({
            method: 'POST',
            url: urlRoot + 'article/class',
            data: { class_name: colTitle },
            header: {
                'Content-type': 'application/json'
            },
        }).then((json) => {
            alert('新建分类专栏 ' + json.data.class_name + ' 成功!');
            closeBar(add_col_bar);
            add_col_bar_title.value = '';
            renderColumn();
        }, (error) => {
            alert(error);
            closeBar(add_col_bar);
        });
    }
    add_col_bar_btn.addEventListener('click', addColumn);

    // 分类专栏 options (包含了专栏操作：管理、编辑、删除)
    let edit_col_bar = document.querySelector('.edit_col_bar');//编辑分类专栏 确认框
    let delete_col_bar = document.querySelector('.delete_col_bar');// 删除分类专栏 确认框
    let col_id;//分栏id
    let col_title;//分栏名
    column_list.addEventListener('click', function (e) {
        let cname = e.target.className;
        let li;
        let col_name;
        if (cname === 'manage_opt_box' ||
            cname === 'edit_opt_box' ||
            cname === 'delete_opt_box') {
            li = e.target.parentNode.parentNode;
            col_name = li.querySelector('.col_name');
            col_id = li.dataset.id;
            col_title = col_name.textContent;
        } else {//如果没有点击工具栏按钮，就结束判断
            return;
        }
        if (cname === 'manage_opt_box') {
            // 管理按钮 逻辑（显示内部所有文章，可以从分类中删除
            renderArticleByClassId();
            showArtiInCol();
        } else if (cname === 'edit_opt_box') {
            // 编辑按钮 逻辑
            col_newTitle_in.value = col_title;
            showBar(edit_col_bar);
            col_newTitle_in.focus();
        } else if (cname === 'delete_opt_box') {
            showBar(delete_col_bar);
        }
    });


    // 编辑分栏框 确认/取消按钮 及 事件绑定
    let col_newTitle_in = document.querySelector('.col_newTitle_in');
    let edit_col_bar_btn = document.querySelector('.edit_col_bar_btn');
    // 编辑分栏框 enter监听
    col_newTitle_in.addEventListener('keydown', function (e) {
        if (edit_col_bar.style.display !== 'none') {
            if (e.key === 'Enter') {
                editColumn();
            }
        }
    });
    let editColumn = function () {
        let newTitle = col_newTitle_in.value;
        if (newTitle === '') {
            console.log('输入不能为空');
            return;
        }
        ajax({
            method: 'PUT',
            url: urlRoot + 'article/class',
            data: {
                id: col_id,
                class_name: newTitle,
            },
            header: {//post/put/delete 修改为 application/json
                'Content-type': 'application/json'
            },
        }).then((json) => {
            alert('修改分类专栏' + newTitle + '成功');
            closeBar(edit_col_bar);
            col_newTitle_in.value = '';
            renderColumn();
        }, (error) => {
            alert(error);
            closeBar(edit_col_bar);
        });
    }
    edit_col_bar_btn.addEventListener('click', editColumn);

    // 删除 确认/取消按钮 及 事件绑定
    let del_confrimBtn = document.querySelector('.del_confrimBtn');
    let del_cancelBtn = document.querySelector('.del_cancelBtn');
    let deleteColumn = function () {//删除对应的col_id
        if (col_id == -1) {//未分类不可删除
            closeBar(delete_col_bar);
            console.log('未分类不可删除');
            return;
        }
        ajax({
            method: 'DELETE',
            url: urlRoot + 'article/class',
            data: { id: col_id },//data为传入的json数据
            header: {//post/put/delete 修改为 application/json
                'Content-type': 'application/json'
            },
        }).then((json) => {
            alert('删除分类专栏id[' + json.data.id + ']成功!');
            renderColumn();
            closeBar(delete_col_bar);
        }, (error) => {
            alert(error);
            closeBar(delete_col_bar);
        });
    }
    del_cancelBtn.addEventListener('click', function () {//取消
        closeBar(delete_col_bar);
    });
    del_confrimBtn.addEventListener('click', deleteColumn);//确认删除


    // 管理分类下的文章
    let colH3 = document.querySelector('.classified_column_content>h3');
    let artiTemplateInCol = (dataId, artiTitle) =>
        `<li data-id="${dataId}">
        <div class="arti_title">
            <span class="arti_title_span">${artiTitle}</span>
        </div>
        <div class="arti_info">
            <div class="opt_box">
                <a href="javascript:;" class="edit_opt_box">编辑</a>
                <a href="javascript:;" class="check_opt_box">浏览</a>
                <a href="javascript:;" class="delete_opt_box">删除</a>
            </div>
        </div>
    </li>`
    let renderArticleByClassId = function () {
        artiInColumn.children[0].innerHTML = '';
        colH3.innerHTML = col_title;
        ajax({
            method: 'GET',
            url: urlRoot + 'article/getArticle',
            data: { class_id: col_id },
        }).then((json) => {
            json.data.forEach(arti => {
                let html = util.str2Html(artiTemplateInCol(arti.id, arti.title, arti.create_time, col_title));
                artiInColumn.querySelector('ul').appendChild(html);
            });

        }, (error) => {
            alert('渲染文章时发生错误：\n' + error);
        });
    }
    // 专栏分类下文章按钮事件监听
    artiInColumn.addEventListener('click', async function (e) {
        let acname = e.target.className;
        let li;
        if (acname === 'edit_opt_box' || acname === 'check_opt_box' || acname === 'delete_opt_box') {
            li = e.target.parentNode.parentNode.parentNode;
            arti_id = li.dataset.id;
        } else {
            return;
        }
        if (acname === 'edit_opt_box') {
            w.location.href = `${util.getCurrRootUrl()}editor.html?id=${arti_id}`;
        } else if (acname === 'check_opt_box') {
            // 页面重定向到博客展示此文章页
            w.location.href = `${util.getCurrRootUrl()}showpage.html?id=${arti_id}`;
        } else if (acname === 'delete_opt_box') {
            ajax({
                method: 'GET',
                url: urlRoot + 'article/getArticle',
                data: {
                    id: arti_id
                },
            }).then((json) => {
                let title = json.data[0].title;
                let content = json.data[0].content;
                if (json.data[0].class_id === -1) {
                    alert('该文章无法被从此分类中删除');
                    return;
                }
                removeArtiFromCol(arti_id, title, content);
            }, (error) => {
                alert(error);
            });
        }
    });
    // 移除文章的分类，分类变为未分类
    let removeArtiFromCol = function (arti_id, title, content) {
        ajax({
            method: 'PUT',
            url: urlRoot + 'article/updateArticle',
            data: {
                id: arti_id,
                class_id: -1,
                title: title,
                content: content,
            },
            header: {//post/put/delete 修改为 application/json
                'Content-type': 'application/json'
            },
        }).then(() => {
            alert('从分类移除文章[' + title + ']成功!');
            li.remove();
            renderArticle();
            renderColumn();
        }, (error) => {
            alert(error);
        });
    }

    //  ——————————分类专栏部分 结束————————————




    /**
     * test专用位置
     */
    {
        // Promise封装的ajax：请求模板
        // ajax({
        //     method: 'GET',
        //     url: '',
        //     data: {},//data为传入的json数据
        //     header: {//post/put/delete 修改为 application/json
        //         'Content-type': 'application/x-www-form-urlencoded'
        //     },
        // }).then((data) => {
        //     console.log(data);
        //     closeBar('这里输入要关闭的窗口');
        // }, (error) => {
        //     alert(error);
        //     closeBar('这里输入要关闭的窗口');
        // });
    }
    /**
     * test专用位置
     */
})(window);